package sisdroid.framework.rest;

import java.util.HashSet;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sisdroid.framework.model.InfoPackage;
import sisdroid.framework.model.Net;
import sisdroid.framework.model.InfoPackage.InformationData;


/**
 * Wraps a RestClient and learn it to talk Sis Rest Protocol.
 * 
 * @author Morten Nissen
 *
 */
public class SisRestClient
{
	
	static final String REST_ENDPOINT		= "http://fleet.logodan.dk/sis/";
	static final String REST_METHOD_STORE 	= "Information/create";
	static final String REST_METHOD_LOOKUP	= "Information/search";
	static final String REST_METHOD_LISTALL	= "Location/all";
	
	
	
	RestClient _client;
	
	
	public SisRestClient( sisdroid.framework.SisFactory fac )
	{
		_client = fac.createRestClient();
	}
	
	public Set< sisdroid.framework.model.Net > listAll()
	{
		
		
		
		JSONObject json = null;
		String strResult = _client.get( REST_ENDPOINT + REST_METHOD_LISTALL + "" );
		try 
		{
			json = new JSONObject( strResult );
			json.toString();
		}
		catch (JSONException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public Set<InfoPackage> Search( Set<Net> locations, Set<String> filter )
	{
		HashSet<InfoPackage> r = new HashSet<InfoPackage>();
		String urlfilter = "/";

		for ( String s : filter )
		{
			urlfilter += s;
			urlfilter += "+";
		}
		
		urlfilter = urlfilter.substring(0, urlfilter.length() - 1 );

		
		String URL = REST_ENDPOINT + REST_METHOD_LOOKUP + urlfilter;
		String body = NetListToJsonString( locations );
		
		String result = _client.post( URL, body );
		
		
		try 
		{
			JSONArray json = new JSONArray( result );

			
			for ( int i = 0; i < json.length(); i++ )
			{
				InfoPackage ip = new InfoPackage();
				JSONObject	jo = (JSONObject) json.get( 0 );
				
				JSONArray arr = jo.getJSONArray("InformationsData");
				
				/**
				 *             "id": 11,
            	 *				"Tags": [
                 *					{
                 *   					"Tag": "Homepage",
                 *   					"Id": "313cc44f-fe1a-4d0f-8a26-4c07d99f019b"
                 *					}
            	 *					],
            	 * 				"Data": "url:Http://www.logodan.dk",
            	 * 				"Description": "Test beskrivelse",
            	 * 				"ValidUntil": "/Date(253402297199999+0100)/",
            	 *				"Type": null
				 */
				for ( int ii = 0; ii < arr.length(); ii++ )
				{
					JSONObject pack = (JSONObject) arr.get( ii );
					String data = pack.getString("Data" );
					String desc = pack.getString( "Description" );
					String type = pack.getString( "Type" );
					ip.addInfofmationData( type, data, desc );
				}

				
				String s =   jo.getJSONObject( "Information" ).getString( "Titel" );

				ip.setTitle( s );
				
				r.add( ip );
				
			}
			
			
		} 
		catch (JSONException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return r;
		
		
		
	}
	
	
	
	public void Store( InfoPackage ip, Set<Net> locations )
	{
		StringBuilder sb = new StringBuilder();
		sb.append( InfoPackageToJsonString( ip ) );
		sb.append( ", \"Lokationer\":" );
		sb.append( NetListToJsonString( locations ) );
		sb.append( "}" );
		String URL = REST_ENDPOINT + REST_METHOD_STORE;
		
		_client.post(URL, sb.toString() );
		
	}
	
	private String NetListToJsonString( Set<Net> s )
	{
		String result = "[";
		boolean first = true;
	    	
//	    	"[{\n\t\"SearchString\":\"String content\",\n\t\"Type\":\"String content\"\n}]"
		for ( Net l : s )
		{
			if ( ! first ) result += ",";
			
			result +=  "{\"Value\":\"";
			result +=  l.getValue();
	    	result +=  "\",\"Type\":\"";
	    	result +=  l.getType();
	    	result +=  "\"}";
	    	first = false;
		}
		result +=  "]";
		return result;
	}
	
	private String InfoPackageToJsonString( InfoPackage ip )
	{
		StringBuilder sb = new StringBuilder();
		
		sb.append( "{" );
		sb.append("\"Information\":{");
		sb.append("\"Titel\":\"");
		sb.append( ip.getTitle() );
		sb.append( "\"},\"InformationsData\":[" );
		
		for ( int i = 0; i < ip.GetInformationCount(); i++ )
		{
			InformationData id = ip.getInformationAt( i );
			if ( i > 0 )
			{
				sb.append(",");
			}
			sb.append("{\"Description\":\"");
			sb.append( id.getDescription() );
			sb.append( "\",\"Data\":\"");
			sb.append( id.getData() );
			sb.append( "\",");
			sb.append( "\"Type\":\"" );
			sb.append( id.getType() );
			sb.append( "\",\"Tags\":[{\"Tag\":\"MyTag\"},{\"Tag\":\"MyOtherTag\"} ]}");
		
		}
		sb.append("]" );
		
		
		return sb.toString();
	}
}
